package com.example.ocrbackend;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

@RestController
public class Service {
    @CrossOrigin()
    @PostMapping("/uploadImage")
    public void postImage(@RequestParam("inputImage") String inputImage) throws IOException, InterruptedException {
        String accessToken = getAccessKey();

        JSONObject ocrResult = ocrAPI(inputImage, accessToken);
        JSONArray words = ocrResult.getJSONArray("words_result");
        if (words != null){
            List<String> wordsList = words.toList(JSONObject.class).stream().map((it)->
                it.getString("words")
            ).toList();

            String result = String.join("\n", wordsList);
            ocrResult.put("image", inputImage);
            ocrResult.put("result", result);
            sendInfo(inputImage, result);
        }
        System.out.println(ocrResult.toString());
    }


    private JSONObject ocrAPI(String newImage, String accessToken) throws IOException, InterruptedException {
        OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + URLEncoder.encode(newImage));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        return JSONObject.parse(response.body().string());
    }


    private String getAccessKey() throws IOException, InterruptedException {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=p5vwwkp8iXIZZHmPihLTPGo3&client_secret=VekcdDO7DcBmckkClU0W0QYU2IiMc23t";

        HttpClient httpClient = HttpClient.newBuilder().build();
        HttpRequest httpRequest = HttpRequest.newBuilder().GET()
                .uri(URI.create(url))
                .build();

        HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

        JSONObject result = JSONObject.parse(response.body());

        return result.getString("access_token");
    }

    @GetMapping("/sendInfo")
    public void sendInfo(String image, String content) throws IOException {
        JSONObject ocrResult = new JSONObject();
        ocrResult.put("image", image);
        ocrResult.put("result", content);

        WebSocketServer.sendInfo(ocrResult.toString());
    }
}
